﻿using System;
using System.Collections.Generic;
using System.Linq;
using Prism.Mvvm;
using IntoMes.Global;
using IntoMes.Models;
using IntoMes.PLC;

namespace IntoMes.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private StationStatusViewModel StationStatus => Locator.Instance.StationStatus;
        private List<string> Recipes => Locator.Instance.SparePartsManage.Recipes.ToList();

        public MainWindowViewModel()
        {
            for (int i = 0; i < 6; i++)
            {
                Triggers.Add(new IntoCommon.Util.TrigR());
            }
            Locator.Instance.Service.StatusChangedEvent += Refresh;
        }

        private List<IntoCommon.Util.TrigR> Triggers = new List<IntoCommon.Util.TrigR>();

        public ProduceData Identity { get; set; } = new ProduceData();

        public SparePartsManageViewModel SparePartsManage => Locator.Instance.SparePartsManage;
        private void Refresh(List<MesGetData> datas)
        {
            try
            {
                int Number = 0;
                for (int i = 0; i < datas.Count; i++)
                {
                    StationStatus.Status[i].IsConnected = datas[i].IsConnected;
                    StationStatus.Status[i].ProModel = SparePartsManage.Recipes.Count()>0?SparePartsManage.Recipes[datas[i].ProModel-1]:"未知";
                    StationStatus.Status[i].ProCount = datas[i].ProCount;
                    StationStatus.Status[i].OKCount = datas[i].OKCount;
                    StationStatus.Status[i].NGCount = datas[i].NGCount;
                    StationStatus.Status[i].ProBeat = datas[i].ProBeat;
                    StationStatus.Status[i].Runtime = datas[i].Runtime;
                    if (i == 0)
                    {
                        SparePartsManage.HasProductNum = StationStatus.Status[i].ProCount;
                    }
                    Number += datas[i].NGCount;
                    
                }
                SparePartsManage.BadProductNum = Number;
                if (SparePartsManage.HasProductNum != 0)
                {
                    float percent = (SparePartsManage.HasProductNum - SparePartsManage.BadProductNum) / (float)SparePartsManage.HasProductNum;
                    SparePartsManage.GoodPercent = $"{(percent * 100).ToString("f2")}%";
                }
                else
                {
                    SparePartsManage.GoodPercent = "0%";
                }


            }
            catch(Exception e)
            {
               
            }
        }

        private string GetResult(int checkVal)
        {
            string result = string.Empty;
            switch (checkVal)
            {
                case 1: result = "OK"; break;
                case 2: result = "NG"; break;
                case 3: result = "OK(Artificial)"; break;
                default: result = "NG"; break;
            }
            return result;
        }
    }
}
